<template>
  <div class="scroll-content">

    <a-typography>
      <a-typography-title class="headline"> <span class="accent">演示</span> 窗口通信</a-typography-title>
    </a-typography>
    <a-typography-paragraph>  </a-typography-paragraph>
    <a-typography-paragraph> 
      启动应用程序，首先打开主窗口，有时候也需要打开可以是子窗口。窗口之间可以依靠IPC进行通信和交互。
    </a-typography-paragraph>
    <a-typography-title :level="5">1、不同形式的窗口</a-typography-title>
    <a-typography-paragraph> 
      打开模态窗口打开后只能操作应用中的该窗口，桌面置顶窗体一般应用于一些桌面挂件，开启后窗口置于所有打开的软件顶层。
    </a-typography-paragraph>
    <a-typography-paragraph>
    <a-space :size="[10, 10]" class="actions" wrap>        
        <a-button size="middle" shape="round" type="default" @click="openWin('vue','#/help', '模态窗体', true,false )">模态窗体</a-button>
        <a-button size="middle" shape="round" type="default" @click="openWin('vue','#/about', '桌面置顶窗体',false,true)">桌面置顶窗体</a-button>
        <a-popover title="系统默认浏览器打开" trigger="hover">
          <template #content>窗口需要关闭 contextIsolation上下文隔离选项，设置<br />webPreferences: {contextIsolation: false }否则用内部窗口</template>
          <a-button size="middle" shape="round" type="default" @click="openExternal('https://gitee.com/')">外部浏览器</a-button>          
        </a-popover>
        <button class="btn" @click="openWin('vue','#/browserview', '内嵌Browserview窗体',false,false)">Browserview</button>
        <button class="btn" @click="openWin('vue','#/webview', '内嵌Webview窗体',false,false)">Webview</button>
       
    </a-space>
    
  </a-typography-paragraph>


    <a-typography-title :level="5">2、窗口控制</a-typography-title>
    <a-typography-paragraph> 
      尝试点击按钮打开不同窗体，再点击"列出窗体信息"，并尝试Close It，窗口id号是1，由于有任务驻留，关闭它以后你可以在右下角再次唤出主界面。
      <br>控制窗体关闭，主要应用在自定义窗口顶部的窗口按钮事件：最小化、最大化。
    </a-typography-paragraph>
    <a-space :size="[10, 10]" class="actions" wrap>
      <a-button size="middle" shape="round" type="primary" @click="openWin('web', 'https://gitee.com/', '窗体A-打开WebUrl')">打开WebUrl</a-button>
      <a-button size="middle" shape="round" type="primary" @click="openWin('html','/public/html/view_example.html', '窗体B-打开HTML文件')">打开HTML</a-button>
      <a-popover title="场景说明" trigger="hover">
        <template #content>弹出置顶的通信子窗口</template>
        <a-button size="middle" shape="round" type="default" @click="openWin('vue', '#/subwindow', '窗体C-通信子窗体', false, true,false)">通信子窗体</a-button>
      </a-popover>
    <a-popover title="场景说明" trigger="hover">
      <template #content>先弹出通信窗体再发消息</template>
      <a-button size="middle" shape="round" type="dashed" @click="sendToWindow('subwindow')">发消息到子窗体</a-button>
    </a-popover>
      <a-popover title="场景说明" trigger="hover">
        <template #content>获取当前应用的所有窗体</template>
        <a-button size="middle" type="link" @click="getAllWin()">列出窗体信息</a-button>
      </a-popover>
    </a-space>

    <p style="height:20px;"> </p>

    <a-table :columns="columns" :data-source="dataList" bordered>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'title'">
          <a>{{ text }}</a>
        </template>

        <template v-else-if="column.dataIndex == 'action'">
          <a-popconfirm v-if="dataList.length" title="关闭它吗?" @confirm="closeWin(record.id)">
            <a>关闭</a>
          </a-popconfirm>
          
          | <a @click="minimizeWin(record.id)">最小化</a>
          | <a @click="expandWin(record.id)">最大化</a>
        </template>
      </template>
    </a-table>

  </div>
</template>

<script setup>
import { ipcApiRoute } from "@/api/main";
import { ipc, isEE } from "@/utils/ipcRenderer";

import {  ref ,onMounted} from "vue";
import { message } from "ant-design-vue";


onMounted(() => {
  isEE ? init() : message.info("Electron环境下，才有消息监听效果");
})

function init() {
  console.log(isEE, "监听子窗体发来的消息");
  // 监听窗口发来的消息
  ipc.removeAllListeners(ipcApiRoute.sms.subToMain);
  ipc.on(ipcApiRoute.sms.subToMain, (event, arg) => {
      message.success(arg, 5);

  })  
}

const columns = [
  {
    title: '窗口Id',
    dataIndex: 'id',
  }, {
    title: '窗口标题',
    dataIndex: 'title',
  },
  {
    title: '操作',
    dataIndex: 'action',
  },
];
const dataList = ref([]);
const onDelete = key => {
  dataList.value = dataList.value.filter(item => item.id !== key);
};

function openWin(type, content="", title = "", isModal = false, isOnTop = false, isRandom = true) {
  if(isEE){
    let width = isRandom ? Math.floor(Math.random() * (301)) + 600 : 800;
    let height = width * 0.7;
    ipc
    .invoke(ipcApiRoute.window.createWindow, {
      type: type,
      windowWidth: width,
      windowHeight: height,
      content: content || "#/help",
      windowName: content.replace("#/",""), // 窗口唯一标识，用于后续通信用
      windowTitle: title || "帮助页面",
      windowFrame: true,
      windowHideMenuBar: true,
      resizable: true, // 可调整大小
      isCenter: isRandom ? true : false, //屏幕居中
      isContextIsolation: false, // 是否开启上下文隔离。
      isModal: isModal,
      windowAlwaysOnTop: isOnTop, //置顶显示
    })
    .then((ret) => {
      console.log("打开窗口", type, ret);
    }) ;    
  }else{
    message.info("Electron环境下，才有窗口打开效果")
  }

}

function getAllWin() {
  isEE ? ipc.invoke(ipcApiRoute.window.getAllWindow).then((ret) => {
    console.log("所有窗口信息", ret);
    dataList.value = ret;
  }) : message.info("Electron环境下，才能获取窗体信息",3);
}

function minimizeWin(id=0) {
  ipc.invoke(ipcApiRoute.window.minimizeWindow, id).then((ret) => {
    ret == "success" ? message.info(ret, 3): message.error(ret, 3)
  });
}
function closeWin(id=0) {
  ipc.invoke(ipcApiRoute.window.closeWindow, id).then((ret) => {
    ret == "success" ? onDelete(id) : message.error(ret, 3)
  });
}
function expandWin(id=0) {
  ipc.invoke(ipcApiRoute.window.expandWindow, id).then((ret) => {
    ret == "success" ? message.info(ret, 3): message.error(ret, 3)
  });
}

function openExternal(url) {     
  //如果启用了上下文隔离( ontextIsolation: true), Electron 13+版本设置默认是启用的。
  //需要设置preload，通过contextBridge暴露的electron对象，及暴露的openExternal方法。
  if (window.electron && window.electron.openExternal) {
    window.electron.openExternal(url).then(() => {
      message.info('启用上下文隔离，需设置preload暴露electron.openExternal方法打开',8);
    }).catch((error) => {
      console.error('打开网页时出错:', error);
    });
  } else {
    //如果不启用上下文隔离( ontextIsolation: false)，则渲染进程中可直接使用electron对象调用openExternal方法。
    const { shell } = require('electron');
    if (shell.openExternal) { // 确保electron版本支持该方法
      shell.openExternal(url).then(() => {
        message.info('未启用上下文隔离，直接使用electron对象调用openExternal打开',8);
      }).catch((error) => {
        console.error('打开网页时出错:', error);
      });
    } else { 
      message.error('非EE环境，不支持openExternal打开默认浏览器', 8)
      window.open(url);
    }
  }
}

async function sendToWindow(receiver) {  
  const params = {
    receiver: receiver,
    content: '来自父窗体的消息内容。。。'
  }
  ipc.invoke(ipcApiRoute.sms.mainToSub, params).then((ret) => {
     console.log("子窗体返回",ret);
  });
}

</script>

<style lang="less" scoped>
.scroll-content {
  height: 100%;
  margin-right: 5px;
  padding: 10px 30px 30px 20px;
  box-sizing: border-box;
  overflow: auto;
}

@media (min-width: 960px) and (max-width: 1299px) {
  .scroll-content {
    padding: 20px 40px 30px 30px;
  }
}

@media (min-width: 1300px) {
  .scroll-content {
    padding: 30px 50px 30px 50px;
  }
}
#WebView {
  margin-top: 10px;
  border: 1px solid #d0d0d0!important;
  background-color: #85f4b5;
  height: 50px;
  width: 100%;
}
.scroll-content::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 10px;
}

.scroll-content::-webkit-scrollbar-thumb {
  background-color: #888;
  border-radius: 10px;
  border: 2px solid #ffffff;
}

.scroll-content::-webkit-scrollbar {
  width: 10px;
}
.ant-empty-normal{
  margin-block: 1px 0px!important;
}
.headline {
  font-size: 32px;
  line-height: 1.9;
  font-weight: bold;
  letter-spacing: -1.5px;
  margin: 0px auto;
}


html:not(.dark) .accent,
.dark .headline {
  background: -webkit-linear-gradient(315deg, #42d392 25%, #647eff);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
p {
  line-height: 1.8;
  margin-top: 10px;
}

.subtitle {
  line-height: 1.5;
  font-size: 22px;
  margin: 44px auto 16px;
}

.description {
  line-height: 1.5;
  font-size: 15px;
  margin: 10px auto 15px;
}

.actions {
  margin: 10px 6px;

  .btn {
    font-size: 14px;
    line-height: 14px;
    padding: 8px 15px;
    border-radius: 25px;
    display: inline-block;
    border: 0px;
    cursor: pointer;
    font-weight: 400;
    text-decoration: none;
    background: -webkit-linear-gradient(315deg, #42d392 25%, #647eff);
    :hover {
      background: -webkit-linear-gradient(115deg, #42d392 25%, #647eff);
    }
  }
}
</style>
